<template>
  <el-drawer
    size="90%"
    v-model="dialogVisibled"
    :before-close="handleClose"
    :title="dialogTitle"
    :close-on-click-modal="false"
    @open="handleDialogOpen"
  >
    <el-divider />
    <div
      style="
        box-shadow: 0 4px 4px #00152914;
        margin-left: 3px;
        margin-right: 3px;
        background-color: white;
      "
    >
      <el-tabs v-model="activeName" style="margin-left: 10px">
        <el-tab-pane label="表单基本信息" name="formBaseMsg">
          <div>
            <div style="padding: 10px">
              <el-form
                ref="ruleFormRef"
                :model="model"
                status-icon
                :rules="rules"
                label-width="auto"
              >
                <el-form-item label="表单名称：" prop="FormName">
                  <el-input
                    v-model="model.FormName"
                    placeholder="请输入表单名称"
                    maxlength="20"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
                <el-form-item label="所属部门：" prop="DepartmentId">
                  <el-tree-select
                    placeholder="请选择部门"
                    v-model="model.DepartmentId"
                    :data="departmentList"
                    :disabled="model.FormId !== '' ? true : false"
                    check-strictly
                    :default-expand-all="true"
                    :render-after-expand="false"
                  >
                  </el-tree-select>
                </el-form-item>
                <el-form-item label="表单备注：" prop="FormRemark">
                  <el-input
                    clearable
                    v-model="model.FormRemark"
                    maxlength="200"
                    placeholder="请输入表单备注"
                    show-word-limit
                    type="textarea"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="设计表单" name="designerForm">
          <div>
            <v-form-designer
              :form-json="formJsonArry"
              :form-data="formDataArry"
              style="margin-top: 25px"
              ref="vfDesigner"
            ></v-form-designer>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <el-button icon="Close" size="large" type="danger" plain @click="handleClose"
        >取消</el-button
      >
      <el-button type="primary" size="large" icon="Check" plain @click="submitForm"
        >保存</el-button
      >
    </template>
  </el-drawer>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, reactive, ref } from "vue";
import { ArrowLeft, Close } from "@element-plus/icons-vue";
import { ElMessage, FormInstance } from "element-plus";
import { FormModel } from "@/model/form";
import { GetFormByFormId, InsertForm, UpdateForm } from "@/api/form";
import { getDepartmentTree } from "@/api/overallAuthApi";
import { treeOutPut } from "@/model/public/treeModel";
import { FormRules } from "element-plus/es/components/form/src/types";
import { DataStateEnum } from "@/enum/public";
export default defineComponent({
  props: {
    isVisibles: {
      type: Boolean,
    },
    dialogTitle: { type: String },
    formId: {
      type: String,
      required: true,
    },
  },

  setup(props, context) {
    //#region  初始化和变量

    var formJsonArry = reactive<any>({});
    var formDataArry = reactive<any>({});

    //步骤id
    const activeName = ref("formBaseMsg");

    //表单ref
    const vfDesigner = ref();

    //表单json
    const formJson = ref<any>("");

    //部门数据
    const departmentList = ref<treeOutPut[]>([]);

    //模型
    var model = ref<FormModel>({
      FormId: "",
      DepartmentId: undefined,
      FormName: "",
      FormData: "",
      FormJson: "",
      TypeId: undefined,
      FormRemark: "",
      DataState: DataStateEnum.Enable,
    });

    //打开时加载
    const handleDialogOpen = function () {
      activeName.value = "formBaseMsg";
      resetForm(ruleFormRef.value);
      vfDesigner.value.clearDesigner();
      getCorporationDepartmentListMsg();
      if (props.formId != "") {
        getFormByFormId(props.formId);
      } else {
        model.value.FormName = "";
        model.value.TypeId = undefined;
        model.value.DepartmentId = undefined;
        model.value.FormJson = "";
        model.value.FormData = "";
        model.value.DataState = DataStateEnum.Enable;
        model.value.FormId = "";
        model.value.FormRemark = "";
      }
    };

    //#endregion

    //#region  验证规则

    //注册验证
    const ruleFormRef = ref<FormInstance>();
    const rules = reactive<FormRules<typeof model.value>>({
      FormName: [
        {
          required: true,
          message: "请填写表单名称!",
          trigger: "blur",
        },
      ],
      DepartmentId: [
        {
          required: true,
          message: "请选择所属部门!",
          trigger: "change",
        },
      ],
    });
    //清除验证
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    //#endregion

    //#region  事件

    //获取部门数据
    const getCorporationDepartmentListMsg = function () {
      getDepartmentTree().then(({ data, code, msg }) => {
        if (code == 200) {
          departmentList.value = data;
        } else {
          ElMessage.warning(msg);
        }
      });
    };

    //获取当前表单信息
    const getFormByFormId = function (formId: string) {
      GetFormByFormId({ formId: formId }).then(({ data, code, msg }) => {
        if (code == 200) {
          model.value = data;
          nextTick(() => {
            vfDesigner.value.setFormJson(data.FormJson);
          });
        } else {
          ElMessage.warning(msg);
        }
      });
    };

    //验证表单
    const verifyForm = async () => {
      var isTrue = ref<boolean>();
      formJson.value = vfDesigner.value.getFormJson();
      if (formJson.value.widgetList.length > 0) {
        isTrue.value = true;
      } else {
        isTrue.value = false;
      }
      return isTrue;
    };

    //验证表单基本信息
    const verifyFormBaseMsg = async (formEl: FormInstance | undefined) => {
      var isTrue = ref<boolean>();
      if (!formEl) return;
      await formEl.validate((valid) => {
        isTrue.value = valid;
      });
      return isTrue;
    };

    //提交
    const submitForm = async () => {
      const formBaseState = await verifyFormBaseMsg(ruleFormRef.value);
      const formStae = await verifyForm();
      if (formBaseState?.value) {
        if (formStae.value) {
          model.value.FormJson = JSON.stringify(formJson.value);
          model.value.FormData = JSON.stringify(vfDesigner.value.getFieldWidgets());
          if (model.value.FormId !== "") {
            UpdateForm(model.value).then(({ code, msg }) => {
              if (code == 200) {
                handleClose();
                ElMessage.success("更新成功");
              } else {
                ElMessage.warning(msg);
              }
            });
          } else {
            InsertForm(model.value).then(({ code, msg }) => {
              if (code == 200) {
                handleClose();
                ElMessage.success("新增成功");
              } else {
                ElMessage.warning(msg);
              }
            });
          }
        } else {
          ElMessage.error("表单无任何设计内容!");
        }
      }
    };

    //是否显示dialog
    const dialogVisibled = computed(() => {
      return props.isVisibles;
    });
    //关闭事件
    const handleClose = () => {
      context.emit("closeBnt");
    };

    //#endregion

    return {
      ArrowLeft,
      Close,
      activeName,
      rules,
      ruleFormRef,
      dialogVisibled,
      handleClose,
      handleDialogOpen,
      submitForm,
      vfDesigner,
      formJson,
      model,
      departmentList,
      formJsonArry,
      formDataArry,
    };
  },
  components: {},
});
</script>

<style lang="scss">
.el-header.main-header {
  display: none !important;
}

.el-divider__text.is-left {
  font-size: 20px;
}
</style>
